<?
class AnnotationInvoker {
	
	protected $reflectionClass;
	
	/**
	 * only if in @validate tag class name eq "this". then we must pass already created action instance.
	 */
	protected $instance;
	
	public function __construct($reflectionClass, $instance = null) {
		if (! is_string ( $reflectionClass ))
			$this->reflectionClass = $reflectionClass;
		else
			$this->reflectionClass = new ReflectionClass ( $reflectionClass );
		$this->instance = $instance;
	}
	
	function getDocComment($str, $tag) {
		$matches = array ();
		preg_match ( '/' . $tag . "(.*)(\\r\\n|\\r|\\n)/U", $str, $matches );
		if (isset ( $matches [1] ))
			return trim ( $matches [1] );
		
		return false;
	}
	
	public function regexp(&$template, $prefix, $params) {
		$methods = $this->reflectionClass->getMethods ();
		$instance = $this->reflectionClass->newInstance ($params);
		foreach ( $methods as $method ) {
			$dc = $this->getDocComment ( $method->getDocComment (), '@regexp' );
			if ($dc != false) {
				$regexp = '/<' . $prefix . ':' . $dc . '/';
				$template = preg_replace_callback ( $regexp, array ($instance, $method->getName () ), $template );
			}
		}
		return $template;
	}
	
	public function validate($prop, $val) {
		if ($this->reflectionClass->hasProperty ( $prop )) {
			
			$property = $this->reflectionClass->getProperty ( $prop );
			
			$dc = $this->getDocComment ( $property->getDocComment (), '@validate' );
			if ($dc != false) {
				$validator = new ValidateAnnotation ( $dc, $this->reflectionClass, $this->instance );
				return $validator->execute ( $val );
			}
		
		}
		return $val;
	}
}
?>